// miniprogram/devTools/commapi/commapi.js
import {
  webview
} from '../../router'
const router = require('../../router')

Page({

  data: {
    // 小程序信息
    miniProgram: [{
      name: '微信记账本',
      appId: 'wx7c86e0c731b9b8ef'
    }, {
      name: '微信发票助手',
      appId: 'wx1af4f6aa3a537c1a'
    }, {
      name: '积木宝贝办公',
      appId: 'wx64d6b4b2fbcbc9b6'
    }],
    // 账号信息
    accountInfo: {},
    // 其他信息
    otherInfos: [{
      name: '收货地址',
      methond: 'chooseAddress'
    }, {
      name: '选择发票抬头',
      methond: 'chooseInvoiceTitle'
    }, {
      name: '选择已有的发票',
      methond: 'chooseInvoice'
    }],
    inputValue: '',
    otherContent: '',
    pageContent: '',
    visitContent: '',
    runContent: ''
  },
  onLoad: function (options) {
    this.getAccountInfo()
  },
  onShareAppMessage: function () {

  },
  getAccountInfo() {
    const accountInfo = wx.getAccountInfoSync();
    this.setData({
      accountInfo
    })
  },
  getUserRunData() {
    wx.getWeRunData({
      success: res => {
        // 或拿 cloudID 通过云调用直接获取开放数据
        const cloudID = res.cloudID
        console.log(res)
        // 使用云函数
        wx.cloud.callFunction({
          name: 'wxPower',
          data: {
            action: 'getWeRunData',
            weRunData: wx.cloud.CloudID(cloudID)
          }
        }).then(res => {
          console.log(res)
          this.setData({
            runContent: JSON.stringify(res)
          })
          this.initRunChart()
        })
      }
    })
  },
  getUserPhone(event) {
    let cloudID=event.detail.cloudID
    // 使用云函数
    wx.cloud.callFunction({
      name: 'wxPower',
      data: {
        action: 'getWeRunData',
        weRunData: wx.cloud.CloudID(cloudID)
      }
    }).then(res => {
      console.log(res)
      this.setData({
        runContent: JSON.stringify(res)
      })
      this.initRunChart()
    })
  },
  initRunChart() {
    let runContent = this.data.runContent
    let runData = JSON.parse(runContent)
    runData = runData.result.data.stepInfoList
    var chartComponent = this.selectComponent("#run_chart");
    chartComponent.initLineChart(runData)
  },
  onJumpToMini(e) {
    console.log("onJumpToMini", e)
    let appId = e.currentTarget.dataset.appid
    wx.navigateToMiniProgram({
      appId: appId,
      path: 'pages/index/index'
    }).then(res => {
      console.log("onJumpToMini", res)
    }).catch(err => {
      console.error(err)
    })
  },
  siteSearch() {
    wx.cloud.callFunction({
      name: 'wxPower',
      data: {
        action: 'siteSearch',
        siteSearch: '天气'
      }
    }).then(res => {
      console.log(res)
    })
  },
  pageSearch() {
    console.log(router)
    let pages = []
    for (let key in router) {
      // console.log(key + '---' + router[key])
      if (pages.length < 6)
        pages.push(router[key])
    }
    wx.showActionSheet({
      itemList: pages,
      success: res => {
        console.log(res.tapIndex)
        let tapIndex = res.tapIndex
        this.setData({
          pageContent: pages[tapIndex]
        })
      }
    })
  },
  crateQrcode() {
    if (!this.data.pageContent) {
      wx.showToast({
        title: '请先选择小程序页面',
        icon: 'none'
      })
      return
    }
    wx.showLoading({
      title: '生成中...',
    })
    wx.cloud.callFunction({
      name: 'wxPower',
      data: {
        action: 'createQRCode',
        path: this.data.pageContent
      }
    }).then(res => {
      wx.hideLoading()
      console.log("crateQrcode", res)
      let fileManager = wx.getFileSystemManager(); //获取文件管理器
      let filePath = wx.env.USER_DATA_PATH + '/inner.jpg'; //设置临时路径
      fileManager.writeFile({ //获取到的数据写入临时路径
        filePath: filePath, //临时路径
        encoding: 'binary', //编码方式，二进制
        data: res.result.buffer, //请求到的数据
        success: function (res) {
          console.log("writeFile", res)
          console.log(filePath) //打印路径
          wx.previewImage({ //图片预览
            urls: [filePath],
          })
          wx.hideLoading();
        },
        fail: function (res) {
          console.log(res)
          wx.hideLoading();
        },
      });
    })
  },
  getUserPortrait() {
    wx.cloud.callFunction({
      name: 'wxPower',
      data: {
        action: 'getUserPortrait'
      }
    }).then(res => {
      console.log(res)
      this.setData({
        visitContent: JSON.stringify(res)
      })
    })
  },
  getMonthVisitData() {
    wx.cloud.callFunction({
      name: 'wxPower',
      data: {
        action: 'getMonthVisitData'
      }
    }).then(res => {
      console.log(res)
      this.setData({
        visitContent: JSON.stringify(res)
      })
    })
  },
  chooseAddress() {
    wx.chooseAddress().then(res => {
      console.log("chooseAddress", res)
      this.setData({
        otherContent: JSON.stringify(res)
      })
    }).catch(err => {
      console.error(err)
    })
  },
  chooseInvoiceTitle() {
    wx.chooseInvoiceTitle().then(res => {
      console.log("chooseInvoiceTitle", res)
      this.setData({
        otherContent: JSON.stringify(res)
      })
    }).catch(err => {
      console.error(err)
    })
  },
  chooseInvoice() {
    wx.chooseInvoice().then(res => {
      console.log("chooseInvoice", res)
      this.setData({
        otherContent: JSON.stringify(res)
      })
    }).catch(err => {
      console.error(err)
    })
  },
  jumpToArticle(e) {
    let url = e.currentTarget.dataset.url
    wx.navigateTo({
      url: webview + `?url=${url}`
    })
  },
  onSubscribeMessage(e) {
    wx.requestSubscribeMessage({
      tmplIds: ['X15zp3hfUUqyLMX2jj41BW7OwPi7h71_FNFhyY9GYC4'],
      success: res => {
        let msg = res['X15zp3hfUUqyLMX2jj41BW7OwPi7h71_FNFhyY9GYC4']
        console.log("success", res)
        let errMsg = msg == "reject" ? '授权失败！' : '授权成功！'
        wx.showToast({
          title: errMsg,
          icon: 'none'
        })
      }
    })
  },
  sendSubscribeMessage(e) {
    wx.cloud.callFunction({
      name: 'msgReply',
      data: {
        sendSubscribeMsg: true
      }
    }).then(res => {
      console.log(res)
      let errCode = res.result.errCode
      let errMsg = '请先授权！'
      if (errCode == 43101) {} else if (errCode == 0) {
        errMsg = '发送成功'
      }
      wx.showToast({
        title: errMsg,
        icon: 'none'
      })
    })
  },
  sendUniformMessage(e) {
    // 需要配置permission
    wx.cloud.callFunction({
      name: 'msgReply',
      data: {
        sendUniformMessage: true
      }
    }).then(res => {
      console.log(res)
    })
  },
  clearContent(event) {
    console.log(event)
    let content = event.currentTarget.dataset.content
    let dataObj = {}
    dataObj[content] = ''
    this.setData(dataObj)
  }
})